import './app.scss'
import piscesIcon from './assets/icon/pisces.png'
import {useEffect, useState} from "react";
import Select from "./components/Select.tsx";
import {Star, StarSign, StarSignInfo, TimeSelect} from "../types.ts";
import FortuneText from "./components/FortuneText.tsx";
import Header from "./components/Header.tsx";
import Info from "./components/Info.tsx";
import Main from "./components/Main.tsx";
import initStarSign from "./data/starSign.ts";
import initTimeSelect from "./data/TimeSelect.ts";


function App() {
    const [starSign, setStarSign] = useState<StarSign[]>(initStarSign)
    const [starSignInfo, setStarSignInfo] = useState<StarSignInfo>({})
    const [open, setOpen] = useState(false);
    const [url, setUrl] = useState("https://api.vvhan.com/api/horoscope?type=pisces&time=today")
    const [timeSelect, setTimeSelect] = useState<TimeSelect[]>(initTimeSelect)

    useEffect(() => {
        async function getStarSignInfo() {
            const res = await fetch(url)
            const data = await res.json()
            setStarSignInfo(data.data)
        }

        getStarSignInfo()
    }, [url])
    // 切换星座
    const handleChangSelect = (star: Star) => {
        // 修改原始数据的选中状态
        setStarSign(starSign.map(_star => {
            _star.active = star.key === _star.key;
            return _star;
        }))
        // 更改请求的url
        const currentTime = timeSelect.find(_time => _time.active)?.value || "today";//选择当前选中的时间
        const newUrl = `https://api.vvhan.com/api/horoscope?type=${star.key}&time=${currentTime}`
        setUrl(newUrl);
    }

    // 切换时间
    const handleChangeTime = (time: TimeSelect) => {
        setTimeSelect(
            timeSelect.map(_time => {
                _time.active = _time.value === time.value;
                return _time;
            })
        )
        // 更改请求的url
        const currentStar = starSign.find(x => x.active)?.key || "pisces";//找到当前选中的星座
        const newUrl = `https://api.vvhan.com/api/horoscope?type=${currentStar}&time=${time.value}`
        setUrl(newUrl);
    }
    return (
        <main id="app">
            {/*头部*/}
            <Header handleChangeTime={handleChangeTime} timeSelect={timeSelect}
                    src={starSign?.find(x => x.active)?.icon || piscesIcon}/>
            {/*打开筛选*/}
            <Info date={starSign?.find(x => x.active)?.date || '02.19 - 03-20'} setOpen={setOpen}
                  title={starSignInfo?.title}/>
            {/*核心内容*/}
            <Main starSignInfo={starSignInfo}/>
            {/*运势*/}
            <FortuneText fortuneText={starSignInfo?.fortunetext}/>
            {/*星座选择*/}
            <Select onChangSelect={handleChangSelect} open={open} setOpen={setOpen} starSign={starSign}/>
        </main>
    )
}

export default App;